#!/usr/bin/env perl

use strict;

my $fasta = @ARGV[0];
my $label = @ARGV[1];
my $option = @ARGV[2];
(my $decoy1 = $fasta) =~ s/fasta$/decoy.$&/;
(my $decoy2 = $fasta) =~ s/fasta$/decoy_target.$&/;
if($#ARGV!=2){
print <<Usage;
perl decoy_database.pl [.fasta] [decoy label] [<1>:seperated decoy database or <2>:combined decoy-target database]
eg: perl decoy_database.pl xxx.fasta "##" 1
Usage
exit;
}

open(FH,$fasta) or die "Can't open fasta file $fasta $!\n";
if($option == 1){
  open(OUT,">","$decoy1") or die "Can't wrote decoy.$fasta$!\n";
}else{
  open(OUT,">","$decoy2") or die "Can't wrote decoy-target.$fasta $!\n";
}
my $decoy;
my $seq_len = 60;
my $temp;
while(<FH>){
  print OUT if $option == 2;
  chomp;
  if(/^>/){
    if((length $temp) > 0 ){
       $temp = join "\n", (($temp = reverse $temp) =~ /(.{$seq_len}|.*)/g);
       $decoy .= "\n".$temp;
    }
    s/^.//;
    $decoy .= ">".$label.$_;
    $temp = "";
  }else{
    $temp .= $_;
  }
}

if((length $temp) > 0){
   $temp = join "\n", (($temp = reverse $temp) =~ /(.{$seq_len}|.*)/g);
   $decoy .= "\n".$temp;
}

close(FH);
print OUT $decoy;
close(OUT);

